package networkcontroller.packet;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * class for segment packet - conatining data of one segment of file
 * 
 * @author maciek
 * 
 */
public class SegmentPacket extends Packet
{
	/**
	 * data of segment
	 */
	private byte[]	data;

	/**
	 * constructs segment with given data
	 * 
	 * @param data
	 *            segment data
	 */
	public SegmentPacket(byte[] data)
	{
		super(true, false);
		type = Packet.SEGMENT_CODE;
		this.data = data;
		createPacket();
	}

	/**
	 * creates packet data
	 */
	protected void createPacket()
	{
		try
		{
			ByteArrayOutputStream baos;
			long size;
			size = MESSEGE_TYPE_SIZE + data.length;
			baos = new ByteArrayOutputStream(SIZE_SIZE + MESSEGE_TYPE_SIZE + data.length);
			DataOutputStream dos = new DataOutputStream(baos);
			dos.writeLong(size);
			dos.writeByte(type);
			dos.write(data);
			packetData = baos.toByteArray();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
